#include "BitmapFont.h"
#include "../Tiny XML/tinyxml.h"


#include <string>
using std::string;


#include "../wrappers/CSGD_TextureManager.h"
#include "../wrappers/SGD_String.h"


CBitmapFont* CBitmapFont::GetInstance( void )
{
	static CBitmapFont sInstance;
	return &sInstance;
}

CBitmapFont::CBitmapFont(void)
{
}


CBitmapFont::~CBitmapFont(void)
{
}


void CBitmapFont::Print( const char* szText, int nX, int nY, float fScale )
{
	string strText = szText;
	int nCurrLeft = nX;
	vector< CLetter >::iterator letterIter;

	for( unsigned int i = 0; i < strText.size(); i++ )
	{
		letterIter = m_Letters.begin();
		for( ; letterIter != m_Letters.end(); ++letterIter )
		{
			if( strText[i] == letterIter->GetLetter() )
			{
				CSGD_TextureManager::GetInstance()->Draw(
					m_nImageID,
					nCurrLeft, nY, fScale, fScale,
					&letterIter->GetCellRect()
					);
				nCurrLeft += letterIter->GetWidth();
			}
		}

	}
}


bool CBitmapFont::LoadFont( const char* szXmlFile, const char* szImagefile )
{
	//unsigned int size = strlen(szImagefile)*2+2;
	//TCHAR* Imagefile;
	//CSTR_TO_TSTR(Imagefile, size, szImagefile );
	//m_nImageID = CSGD_TextureManager::GetInstance()->LoadTexture( Imagefile );
	assert( m_nImageID != -1 && "CBitmapFont::LoadFont - could not load image" );


	TiXmlDocument doc;

	if( !doc.LoadFile( szXmlFile ) )
		return false;

	TiXmlElement* pRoot = doc.RootElement();
	if( !pRoot )
		return false;

	
	CLetter letter;
	TiXmlElement* pLetter = pRoot->FirstChildElement( "Letter" );
	while( pLetter)
	{
		char cLetter;
		double left, top, right, bottom, width;
		pLetter->SetAttribute("letter", &cLetter );
		pLetter->SetAttribute("left", left );
		pLetter->SetAttribute("right", right );
		pLetter->SetAttribute("top", top );
		pLetter->SetAttribute("bottom", bottom );
		pLetter->SetAttribute("width", width );
		RECT rCell = { left, right, top, bottom };
		
		m_Letters.push_back( CLetter( rCell, cLetter, (int)width ) );
	}

	if( m_Letters.size() >= 52 )
		return true;
	else 
		return false;
}
